package com.wangyadong.hobby.thread;

import org.junit.Assert;

import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

public class IDCountDownLatch {
    private static volatile long i = 0;
    private static final int nNum = 1000;
    private static CountDownLatch start = new CountDownLatch(1);
    private static CountDownLatch done = new CountDownLatch(nNum);

    public synchronized static long next() {
        return (i++);
    }

    public static void main(String[] args) throws InterruptedException {
        IntStream.range(0, nNum).forEach(id -> {
            new Thread(() -> {
                next();
                try {
                    start.await();
                    done.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        });


        start.countDown();
        done.await();

        System.out.println(i);
        Assert.assertTrue(i == nNum);
    }


}
